﻿using Newtonsoft.Json;
using NLog;
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace ZhongKeSite.Common.Helper
{
    public class JsonHelper
    {
        private static ILogger logger = LogManager.GetLogger(typeof(JsonHelper).Name);
        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public static string SerializeObject(object obj)
        {
            try
            {
                return JsonConvert.SerializeObject(obj);
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, ex);
                return string.Empty;
            }
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public static T DeserializeObject<T>(string jsonData)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonData);
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, ex);
                return default(T);
            }
        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            try
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
                {
                    T obj = (T)ser.ReadObject(ms);
                    return obj;
                }
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, ex);
                return default(T);
            }
        }
    }
}
